package com.milkway.auth;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.lang3.StringUtils;

import com.milkway.Constants;
import com.milkway.database.DbUtils;

public class Login extends HttpServlet {

  private static final long serialVersionUID = 1L;

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    this.doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    List<String> errors = new ArrayList<>();

    if (StringUtils.isEmpty(username)) {
      errors.add("username is required.");
    }

    if (StringUtils.isEmpty(password)) {
      errors.add("password is required.");
    }
    
    if (errors.size() > 0) {
      loginAgain(req, resp, errors);
      return;
    }

    ResultSetHandler<String> h = new ResultSetHandler<String>() {
      @Override
      public String handle(ResultSet rs) throws SQLException {
        if (!rs.next()) {
          return null;
        }
        return rs.getString(1);
      }
    };
    String sql = "SELECT password FROM user WHERE name=?";
    
    String realPassword = DbUtils.query(sql, h, username);
    
    if (password.equals(realPassword)) {
      req.getSession(true).setAttribute(Constants.HAS_LOGGED_IN, true);
      resp.sendRedirect("index.jsp");
    } else {
      errors.add("password or username is incorrect.");
      loginAgain(req, resp, errors);
    }
  }

  private void loginAgain(HttpServletRequest req, HttpServletResponse resp,
      List<String> errors) throws ServletException, IOException {
    req.setAttribute("errors", errors);
    req.getServletContext().getRequestDispatcher("/page/auth/login.jsp").forward(req, resp);
    return;
  }
}
